package com.chb.utils;

import com.chb.dto.resp.AppleRespDto;
import com.chb.entity.LeadsFileDto;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

/**
 * @description:
 * @author: chb
 * @create: 2022-06-07 16:48
 **/
public class BeanCopyUtil {

    public static <S,T> T copyBean(S source, Supplier<T> target, BiConsumer<S,T> handler){
        if(source == null || target == null){
            return null;
        }
        T t = target.get();
        BeanUtils.copyProperties(source,t);
        if(handler != null){
            handler.accept(source,t);
        }
        return t;
    }

    public static <S,T> List<T> copyBeanList(List<S> source, Supplier<T> target, BiConsumer<S,T> handler){
        if(source == null || target == null){
            return Collections.emptyList();
        }
        List<T> copyList = new ArrayList<>(source.size());
        for (S s : source) {
           T t = copyBean(s,target,handler);
           copyList.add(t);
        }
        return copyList;
    }

    private static <S, T> T copyBean(S s, Supplier<T> target) {
        return copyBean(s,target,null);
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        LeadsFileDto leadsFileDto = new LeadsFileDto();
        leadsFileDto.setId(90L);
        leadsFileDto.setFilePath("jjhhhjjmnn");
        // AppleRespDto appleRespDto = BeanCopyUtil.copyBean(leadsFileDto, AppleRespDto::new, (s,t) -> {
        //     t.setId(32L);
        //     t.setFilePath("djhfjdcl999");
        // });
        // System.out.println(appleRespDto);

        LeadsFileDto l1 = new LeadsFileDto();
        l1.setId(70L);
        l1.setFilePath("jjhhhjjmnn");
        LeadsFileDto l2 = new LeadsFileDto();
        l2.setId(90L);
        l2.setFilePath("jjhhhjjmnn");
        List<LeadsFileDto> leadsFileDtos = new ArrayList<>();
        leadsFileDtos.add(l1);
        leadsFileDtos.add(l2);
        System.out.println(leadsFileDtos);
        List<AppleRespDto> appleRespDtos = copyBeanList(leadsFileDtos, AppleRespDto::new, (s, t) -> {
            t.setId(s.getId() + 1);
            t.setFilePath(s.getFilePath() + "====9---");
        });
        String url = "https://restapi.amap.com/v3/geocode/regeo?key=3da9257f1521c50bbfc99aa0839c7ce2&location=118.8119430,32.0178120";
        HttpRequest request = HttpRequest.newBuilder(URI.create(url)).GET().build();
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }

}
